package com.atguigu.chapter07;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/6 9:12
 */
public class Flink25_ProcessFunction_SideOutput {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forMonotonousTimestamps()
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );

        KeyedStream<WaterSensor, String> sensorKS = sensorDS.keyBy(sensor -> sensor.getId());

        SingleOutputStreamOperator<Long> resultDS = sensorKS
                .process(
                        new KeyedProcessFunction<String, WaterSensor, Long>() {

                            private long count = 0L;

                            OutputTag<String> outputTag = new OutputTag<String>("high") {
                            };

                            @Override
                            public void processElement(WaterSensor value, Context ctx, Collector<Long> out) throws Exception {
                                if (value.getVc() > 5) {
                                    ctx.output(outputTag, "当前水位是" + value.getVc() + ",大于阈值5！！！");
                                }
                                out.collect(++count);
                            }


                        }
                );

        resultDS.print("result");

        OutputTag<String> outputTag1 = new OutputTag<String>("high") {
        };
        resultDS.getSideOutput(outputTag1).print("high");


        env.execute();
    }
}

/*


 */